import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

main() => runApp(SampleApp());

class SampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "SampleApp",
      theme: ThemeData(primarySwatch: Colors.amber),
      home: new SampleAppPage(),
    );
  }
}

class SampleAppPage extends StatefulWidget {
  SampleAppPage({Key key}) : super(key: key);

  @override
  _SampleAppPageState createState() => new _SampleAppPageState();
}

class _SampleAppPageState extends State<SampleAppPage> {
  List widgets = <Object>[];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  //发起异步的http请求,不阻塞UI线程
  Future<void> loadData() async {
    //    final httpClient = new HttpClient();
    //    HttpClientRequest resquest = await httpClient.get(
    //        "https://jsonplaceholder.typicode.com/posts", null, null);
    //    var response = resquest.close();
    //    setState(() {
    //      widgets = json.decode(response.toString());
    //    });

    const URL = "https://jsonplaceholder.typicode.com/posts";
    http.Response response = await http.get(URL);
    setState(() {
      widgets = json.decode(response.body);
    });
  }

  Widget getRow(int i) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: new Text("ROW ${widgets[i]["title"]}"),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("沙雕"),
      ),
      body: ListView.builder(
          itemCount: widgets.length,
          itemBuilder: (BuildContext context, int position) {
            return getRow(position);
          }),
    );
  }
}
